package com.tianji.learning.utils;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.time.Duration;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;
@NoArgsConstructor
@AllArgsConstructor(staticName = "of")
@Data
public class DelayTask<D> implements Delayed {
    private Long deadlineNanos;
    private D data;



    public DelayTask(Duration duration, D data) {
        this.deadlineNanos = System.nanoTime() + duration.toNanos();
        this.data = data;

    }


    public static <D> DelayTask<D> of(Duration duration, D data) {
        return new DelayTask<>(System.currentTimeMillis() + duration.toMillis(), data);
    }




    @Override
    public long getDelay(TimeUnit unit) {
        return unit.convert(Math.max(0, deadlineNanos - System.nanoTime()), TimeUnit.NANOSECONDS);
    }

    @Override
    public int compareTo(Delayed o) {
        long l = getDelay(TimeUnit.NANOSECONDS) - o.getDelay(TimeUnit.NANOSECONDS);
        if(l > 0){
            return 1;
        }else if(l < 0){
            return -1;
        }else {
            return 0;
        }
    }
}